angular.
module('staffChange').
component('staffChange', {
  templateUrl:
  'views/app/staff-change/staff-change.template.html',

  controller: function ($scope,$cookies,$http,$window,$location,$rootScope,$routeParams,$compile) {
        $scope.myRights = readCookie('right')
        if ($scope.myRights != undefined){
          if ($scope.myRights.indexOf('user') == -1){
                      swal("没有操作权限", '请联系管理员!', "error").then(function(){
            })
          return false
        }
        
        }
        else{
          $window.location = '/login'
        }

          $scope.name = ''
          $scope.nickName = ''

          $scope.expenses = []
          $scope.shadow = false
          $scope.cellphone = ''
          $scope.cellphoneChange = 0
          $scope.lastIndex = -1
          $scope.openid = ''
          $scope.deposit = 0
          var openid = ''
          $scope.id = $routeParams.id

          var condition = {}
          // get info
          if ($scope.id != undefined){
            $http({
                method: 'post',
                url: '/admin/getUser',
                data : {'session':$cookies.get('sessionID'),id:$scope.id}
            }).success(function(datax) {
              console.log(datax)
                for (var j = 0 ;j < datax.data.expenses.length ; j++){
                  if ((datax.data.expenses[j].date != null) && (datax.data.expenses[j].date != '')){
                  datax.data.expenses[j].dateText = formatDate(datax.data.expenses[j].date)
                }
                else{
                  datax.data.expenses[j].dateText = ''
                }
                }
                $scope._id = datax.data._id
              $scope.name = datax.data.name
              $scope.cellphone = datax.data.cellphone
              $scope.expenses = datax.data.expenses
              $scope.count = datax.count
              $scope.deposit = datax.data.deposit
              
            })          

            if ($routeParams.cellphone != undefined){
                $scope.dis = true
              }
          }


          



        $scope.remove = function(index){
          var id = $scope.expenses[index]._id
          var name = $scope.expenses[index].name
          var expense = $scope.expenses[index].expense
          var time = $scope.expenses[index].time
          swal({
            title: '确定要删除' + name + '吗?',
            text: "",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '删除',
            cancelButtonText : '取消'
          }).then((result) => {
            if (result.value) {
               if (id != undefined){
                $http({
                    method: 'post',
                    url: '/admin/removeExpense',
                    data : {'id':id,'session':$cookies.get('sessionID'),name : name,expense : expense,time : time}
                    
                }).success(function(datax) {
                            if (datax.code == 401){
            $window.location = '/login'
            return false
          }
                  if (datax.code == 200){
                    swal(
                      '删除成功',
                      '',
                      'success'
                    )
                    // splice 
                    $scope.expenses.splice(index,1)           
                  }
                  else{
                    swal(
                      '出错了',
                      '',
                      'error'
                    )
                  }
         
                })                

              // swal(
              //   'Deleted!',
              //   'Your file has been deleted.',
              //   'success'
              // )
              
            }
            else{
              $scope.expenses.splice(index,1) 
            }
          }
          })
        }


          $scope.cellphoneChange = function(){
            $scope.cellphoneChange = 1
          }

          $scope.edit = function(index){
            if ($scope.cellphone == ''){
                                 swal("手机号不能为空!" ,'',"error").then(function(){
                   })   
            }
            else{
              // $scope.lastIndex = index
              // $rootScope.selectedEvent = $scope.expenses[index]
              // $rootScope.cellphone = $scope.cellphone
              // expenseModal.activate()
              // $scope.shadow = false
                            $window.location = '/expense_change?id=' + $scope.expenses[index]._id
            }

          }

        $rootScope.$on("closeModal", function(){
           expenseModal.deactivate()
        });

        $rootScope.$on("CallParentMethod", function(){
           $scope.parentmethod();
        });

        $scope.parentmethod = function() {
            if ($rootScope.currentEvent.date != ''){
               $rootScope.currentEvent.dateText = $rootScope.currentEvent.date
              }
              else{
                $rootScope.currentEvent = ''
              }
            if ($scope.lastIndex != -1){
              $scope.timelineData[$scope.lastIndex] = $rootScope.currentEvent
            }
            else{
              $scope.timelineData.push($rootScope.currentEvent)
            }
            $scope.expenses = $scope.expenses.sort(function(a,b){
              var adate = (a.dateText == '') ? new Date(new Date().getTime() + 365 * 24 * 3600000) : new Date(a.dateText)
              var bdate = (b.dateText == '') ? new Date(new Date().getTime() + 365 * 24 * 3600000) : new Date(b.dateText)
              return bdate - adate})
            $rootScope.currentEvent = undefined
            $scope.lastIndex = -1
            myModal.deactivate()
            $scope.$apply() 
            // task
        }

      $scope.newEvent = function(){
                $rootScope.cellphone = $scope.cellphone
        myModal.activate()
      }

      $scope.newUser = function(){
       var message = ''

          if ($scope.name.length == 0){
            message += '用户姓名不能为空  \n'
          }
          if ($scope.cellphone.length != 11){
            message += '用户手机不正确  \n'
          }
                    if ($scope.deposit < 0){
            message += '预存金不正确  \n'
          }        
          if (message.length != 0){
            swal("信息不全!", message, "error").then(function(){

            })
            return false
          }
          else{
            $scope.shadow = true
            var url = ''
            if ($routeParams.id == undefined){
              url = '/admin/addUser'
            }
            else{
              url = '/admin/editUser'
            }
            
            console.log(url,"?")
            var data = {}
            data.name = $scope.name
            data.cellphone = $scope.cellphone
            data.cellphoneChange = $scope.cellphoneChange
            data.openid = $scope.openid
            data.deposit = $scope.deposit
            if (url == '/admin/editUser'){
              data._id = $scope._id
            }
            console.log(data,'???')
            if ($scope.cellphone != undefined){
              data.cellphone = $scope.cellphone

            }
            else{

            }
            data.session = $cookies.get('sessionID')
            // swal.showLoading()
            console.log(url,'whwhwdh')
            $http({
              method : 'post',
              url : url,
              data : data}).success(function(data){
                if (data.code == 401){
                  $window.location = '/login'
                  return false
                }
                else if (data.code == 402){
                  $scope.shadow = false
                      swal("该手机已存在!请核对手机号！" ,'', "error").then(function(){

                                   }) 
                      return false
                }

               else if (data.code == 200 ){
                  
                  $scope.shadow = false
                  var message = (url == '/admin/addUser') ? '添加成功！' : '修改成功！'
                  swal(message , '',"success").then(function(){
                    // to template list
                    $window.location = 'user_list'
                  })            
                
              }
              else{
                $scope.shadow = false
                                   swal("修改失败!" , '',"error").then(function(){

                                   })    
              }
             
            })
          }
        }



      function formatDate(date){
        var xdate = new Date(date)
        var year = xdate.getFullYear()
        var day = xdate.getDate()
        var month = xdate.getMonth()
        var hour = xdate.getHours()
        var minute = xdate.getMinutes()
        return String(year) + '/' + String(month+1) + '/' + String(day) + ' ' + String(addZeroBefore(hour)) + ':' + String(addZeroBefore(minute))
      }



      function addZeroBefore(n) {
        return (n < 10 ? '0' : '') + n;
      }




        }})



